﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Atmk.WaterMeter.EF.ModelPuls;
using Atmk.WaterMeter.MIS.Datas;
using Atmk.WaterMeter.MIS.Entities.Models;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Storage;
using Microsoft.Extensions.Hosting;
using NLog;

namespace Atmk.WaterMeter.MIS.TimedTask
{
    public class StatisticsService : IHostedService
    {
        private static Timer _timer;
        private static readonly Logger _Logger = LogManager.GetCurrentClassLogger();

        #region Implementation of IHostedService

        /// <summary>
        ///     Triggered when the application host is ready to start the service.
        /// </summary>
        /// <param name="cancellationToken">Indicates that the start process has been aborted.</param>
        public Task StartAsync(CancellationToken cancellationToken)
        {
            ThreadPool.QueueUserWorkItem((state) =>
            {
                _timer = new Timer(is00, "", TimeSpan.FromSeconds(1), TimeSpan.FromMinutes(30));
                //_Logger.Info($"{nameof(SettlementService)}-Timer启动");
            });
            return Task.Delay(5, cancellationToken);
        }

        /// <summary>
        ///     Triggered when the application host is performing a graceful shutdown.
        /// </summary>
        /// <param name="cancellationToken">Indicates that the shutdown process should no longer be graceful.</param>
        public Task StopAsync(CancellationToken cancellationToken)
        {
            if (_timer != null)
            {
                _timer.Dispose();
                _timer = null;
            }
            return Task.Delay(5, cancellationToken);
        }
        private void is00(object state)
        {
            _Logger.Debug("统计检查报时：" + DateTime.Now.ToString("HH"));
            if (DateTime.Now.ToString("HH") == "01")
            {
                Statistic();
            }
        }
        #endregion
        private void Statistic()
        {
            //_Logger.Info($"{DateTime.Now.ToString()}-Statistic启动");
            try
            {
                using (var _context = ContextBuilder.Build())
                {
                    var district_ids = _context.District.Select(m => m.Id).ToArray();
                    //异常表不参与统计
                    var fault_ids = _context.FaultMeter.Select(m => m.CtdeviceId).ToArray();
                    foreach (var item_id in district_ids)
                    {
                        //异常表不参与统计
                        var ctdevice_ids = _context.Meter.Where(m => m.DistrictId == item_id && !fault_ids.Contains(m.CtdeviceId)).Select(m => m.CtdeviceId).ToList();
                        //昨天该片区的用量
                        var dosages = _context.SettlementDay.Where(m => m.ReadTime.Date == DateTime.Now.AddDays(-1).Date && ctdevice_ids.Contains(m.CtdeviceId)&&m.Dosage>0).Sum(m => m.Dosage);
                        var ts = new TopSelect()
                        {
                            DistrictId = item_id,
                            Dosage = Convert.ToDecimal(dosages),
                            CreateDate = DateTime.Now.AddDays(-1).Date
                        };
                        var topselect = _context.TopSelect.FirstOrDefault(m => m.CreateDate.Value.Date == DateTime.Now.AddDays(-1).Date&&m.DistrictId== item_id);
                        if (topselect == null)
                        {
                            _context.Add(ts);
                        }
                        else
                        {
                            topselect.Dosage = ts.Dosage;
                            _context.Update(topselect);
                        }
                    }
                    int resultCount=_context.SaveChanges();
                    _Logger.Debug($"统计完成：{resultCount} 条。 日期：{DateTime.Now.ToString()}" );
                }
            }
            catch (Exception ex)
            {
                _Logger.Error("统计错误：" + ex.Message);
            }
        }
    }
}